package com.github.wxiaoqi.security.common.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

//解决jackson无法正确转换日期的问题 by sixp 2018.2.5
//   yyyy-MM-dd'T'HH:mm:ss'Z'
public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String STANDARD_DATE_FORMAT_UTC = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        Calendar date = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(STANDARD_DATE_FORMAT_UTC);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        try {
            Date dateTime =sdf.parse(jp.getText());
            date.setTime(dateTime);
            return date.getTime();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

}